package com.tomato.modules.id.runner;

import com.tomato.api.id.dataobject.TomatoIdDO;
import com.tomato.modules.id.mapper.TomatoIdMapper;
import com.tomato.modules.id.strategy.IdGeneratorStrategyService;
import com.tomato.modules.id.service.SegmentIdService;
import com.tomato.modules.id.strategy.impl.CachedIdGeneratorStrategy;
import com.tomato.modules.id.strategy.impl.SnowFlakeGenerateStrategy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 初始化
 *
 * @author lizhifu
 * @date 2022/3/18
 */
@Component
public class IdGeneratorRunner implements CommandLineRunner {
    private static final Logger logger = LoggerFactory.getLogger(IdGeneratorRunner.class);
    private static ConcurrentHashMap<String, IdGeneratorStrategyService> generators = new ConcurrentHashMap<>();
    @Resource
    private TomatoIdMapper tomatoIdMapper;
    @Resource
    private SegmentIdService segmentIdService;
    @Override
    public void run(String... args) throws Exception {
        List<TomatoIdDO> tomatoIdDOList = tomatoIdMapper.selectAll();
        tomatoIdDOList.forEach(tomatoId -> {
            logger.info("初始化数据 tomatoId :{}",tomatoId);
            generators.putIfAbsent(tomatoId.getBizType(),new CachedIdGeneratorStrategy(tomatoId.getBizType(), segmentIdService));
            String[] workIds = tomatoId.getWorkId().split(",");
            for (String workId : workIds) {
                logger.info("初始化数据 workId :{}",workId);
                generators.putIfAbsent(tomatoId.getBizType()+"_"+workId,new SnowFlakeGenerateStrategy(Long.parseLong(workId),tomatoId.getSequenceOffset()));
            }
        });
    }

    public IdGeneratorStrategyService getGenerators(String bizType) {
        return generators.get(bizType);
    }
}
